<template>
  <div class="user-container">
    <el-card class="page-header">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-input v-model="keyword" placeholder="按邮箱关键词搜索" clearable @keyup.enter.native="onSearch" style="width: 240px" />
            <el-select v-model="status" placeholder="状态" clearable style="width: 140px">
              <el-option label="全部" value="" />
              <el-option label="启用" value="enabled" />
              <el-option label="禁用" value="disabled" />
            </el-select>
            <el-button @click="onSearch">搜索</el-button>
            <el-button type="primary" @click="handleCreate">新增用户</el-button>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table :data="users" :loading="loading" height="calc(100vh - 250px)">
          <el-table-column prop="email" label="邮箱" min-width="180" />
          <el-table-column prop="username" label="用户名" min-width="140" />
          <el-table-column label="角色" width="140">
            <template #default="{ row }">{{ roleLabel(row.role) }}</template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'danger'">{{ row.isActive ? '启用' : '禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">{{ formatCreateTime(row.createTime) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="360" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="primary" @click="handleResetPassword(row)">重置密码</el-button>
              <el-button link type="warning" @click="toggleStatus(row)">{{ row.isActive ? '禁用' : '启用' }}</el-button>
              <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        class="pagination-container"
        :current-page="pagination.currentPage"
        :page-size="pagination.itemsPerPage"
        :total="pagination.totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 基于 gDialog 的全局弹窗，无本地占位元素 -->
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUsersStore } from '@/stores/users'
import UserModal from '@/components/modal/UserModal.vue'
import ResetPasswordDialog from '@/components/modal/ResetPasswordDialog.vue'
import { addDialog } from '@/components/gDialog'
import { getRoleLabel } from '@/utils/roles'

const usersStore = useUsersStore()
const users = computed(() => usersStore.users)
const pagination = computed(() => usersStore.pagination)
const loading = computed(() => usersStore.loading)

const keyword = ref('')
const status = ref('')

const roleLabel = (r) => getRoleLabel(r)

const formatCreateTime = (d) => {
  if (!d) return ''
  return new Date(d).toLocaleString('zh-CN')
}

const getList = async (page = 1, limit = pagination.value.itemsPerPage) => {
  await usersStore.fetchUsers({ page, limit, email: keyword.value?.trim(), status: status.value })
}

const onSearch = () => getList(1, pagination.value.itemsPerPage)

const handleSizeChange = (val) => getList(1, val)
const handleCurrentChange = (val) => getList(val, pagination.value.itemsPerPage)

// 新建 / 编辑（使用 gDialog 调起）
const handleCreate = () => {
  addDialog({
    title: '新增用户',
    width: '520px',
    component: UserModal,
    props: { isEdit: false },
    callBack: async (data) => {
      if (!data) return
      try {
        await usersStore.createUser(data)
        ElMessage.success('创建成功')
        getList()
      } catch (e) {
        ElMessage.error(e.message || '创建失败')
      }
    }
  })
}

const handleEdit = (row) => {
  addDialog({
    title: '编辑用户',
    width: '520px',
    component: UserModal,
    props: { isEdit: true, editData: row },
    callBack: async (data) => {
      if (!data) return
      try {
        await usersStore.updateUser(row._id || row.id, data)
        ElMessage.success('更新成功')
        getList(pagination.value.currentPage)
      } catch (e) {
        ElMessage.error(e.message || '更新失败')
      }
    }
  })
}

// 启用/禁用
const toggleStatus = async (row) => {
  try {
    await usersStore.updateStatus(row._id || row.id, !row.isActive)
    ElMessage.success('状态已更新')
    getList(pagination.value.currentPage)
  } catch (e) {
    ElMessage.error(e.message || '更新失败')
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await usersStore.deleteUser(row._id || row.id)
      ElMessage.success('删除成功')
      getList(pagination.value.currentPage)
    } catch (e) {
      ElMessage.error(e.message || '删除失败')
    }
  }).catch(() => {})
}

// 重置密码（使用 gDialog 调起）
const handleResetPassword = (row) => {
  addDialog({
    title: '重置密码',
    width: '420px',
    component: ResetPasswordDialog,
    props: { user: row },
    callBack: async (payload) => {
      if (!payload) return
      try {
        await usersStore.resetPassword(row._id || row.id, payload.newPassword)
        ElMessage.success('已重置密码')
      } catch (e) {
        ElMessage.error(e.message || '重置失败')
      }
    }
  })
}

getList()
</script>

<style scoped>
.user-container { display: flex; flex-direction: column; height: calc(100vh - 120px); }
.page-header { margin-bottom: 20px; }
.table-container { flex: 1; overflow-y: auto; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.header-actions { display: flex; align-items: center; gap: 12px; }
.pagination-container { margin-top: 16px; display: flex; justify-content: flex-end; }
</style>


